
#include <string.h>
#include "Buzzer.h"
#include "BSP_Delay.h"
#include "BSP_Buzzer.h"
#include "Timer.h"

#include "Indecator.h"


static void Indecator_Buzzer_Set(uint32_t id, uint32_t state){
	BSP_Buzzer_Set(state ? 1 : 0);
}

	
static Indecator_T buzzerIndecator = {
	.obj = {
		.objId = 0,
		.action = Indecator_Buzzer_Set,
	},
};

void Buzzer_Init(void){
	IndecatorSetting_T permanent;
	memset(&permanent, 0, sizeof(permanent));
	
	BSP_Buzzer_Set(0);
	Indecator_Init();
	Indecator_Set(&buzzerIndecator, Setting_Permanent, &permanent, 0);
	Indecator_Register(&buzzerIndecator);
}


void Buzzer_On(void){	
	static const IndecatorSetting_T temp = {
		.states[State_Off] = {0, 0},		//无效
		.states[State_On] = {1, 0xFFFF},	//唯一有效状态
		.duration = 0,	//永久有效
		.current = State_On,
	};
	
	Indecator_Set(&buzzerIndecator, Setting_Temp, 0, &temp);
}

void Buzzer_Off(void){
	Indecator_Set(&buzzerIndecator, Setting_Permanent, 0, 0);
}

void Buzzer_AsyncBeepMult(uint8_t count, uint32_t onMs, uint32_t offMs){
	IndecatorSetting_T temp;

	if(count == 0){
		return;
	}
	if(onMs < 10 && offMs < 10){
		return;
	}

	temp.states[State_On].state = 1;
	temp.states[State_On].time = onMs / 10;
	temp.states[State_Off].state = 0;
	temp.states[State_Off].time = offMs / 10;
	temp.duration = (onMs / 10 + offMs / 10) * count;	
	temp.current = State_On;
	
	Indecator_Set(&buzzerIndecator, Setting_Temp, 0, &temp);
}


void Buzzer_Beep(uint32_t ms){
	Buzzer_AsyncBeepMult(1, ms, 0);
	BSP_Delay_ms(ms);
}

void Buzzer_BeepDuration(uint8_t count, uint32_t ms){
	Buzzer_AsyncBeepMult(count, ms, ms);
	BSP_Delay_ms(ms * count * 2);
}

int Buzzer_State(void){
	return BSP_Buzzer_State();
}


